#! /bin/sh
#
#
# Start/Stop airmgsd service
#
#
# Copyright (C) 2007 Wireless Cables Inc.
# Copyright (C) 2007 Naranjo, Manuel <manuel@aircable.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 		
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -e

DAEMON="/usr/bin/airmsgd"
PIDDIR=/var/run/airmsgd
PIDFILE=$PIDDIR/pid
DESC="AIRmsgd server"

start_it_up()
{
  if [ ! -d $PIDDIR ]; then
    mkdir -p $PIDDIR    
  fi
  if [ -e $PIDFILE ]; then
    PIDDIR=/proc/$(cat $PIDFILE)
    if [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${DAEMON}" ]; then 
      echo "$DESC already started; not starting."
    else
      echo "Removing stale PID file $PIDFILE."
      rm -f $PIDFILE
    fi
  fi

  echo -n "Starting $DESC: "
  start-stop-daemon --background --start --exec $DAEMON &
  #the daemon fills the pid file
  echo "running..."
}

shut_it_down()
{
  echo -n "Stopping airmsgd"

  if [ -z $( cat $PIDFILE ) ]; then
	return 0
  fi
  
  PID=$(cat $PIDFILE)

  if [ -n "$( ps -ef | grep $PID | grep -v grep )" ]; then

  	kill -TERM $( cat $PIDFILE )
  fi
  
  echo -n "killing the rest"
  PID=$( cat $PIDDIR/* )

  if [ -n "$PID" ]; then  
	kill -TERM $PID
  fi

  echo -n "removing records from dsp"
  
  OPUSH=$(sdptool browse --uuid 0x1105 local | grep "Service RecHandle:" \
            | sed -e "s/Service RecHandle: 0x//g")
  FTP=$(sdptool browse --uuid 0x1106 local | grep "Service RecHandle:" \
	    | sed -e "s/Service RecHandle: 0x//g")
	
  for i in $OPUSH; do				  
      sdptool del $i
  done
  
  for i in $FTP; do
      sdptool del $i
  done
    
  echo "Stopped."
  rm -f $PIDFILE
  rm -f $PIDDIR/*
}

case "$1" in
  start)
    start_it_up
  ;;
  stop)
    shut_it_down
  ;;
  restart|force-reload)
    shut_it_down
    sleep 1
    start_it_up
  ;;
  *)
    echo "Usage: /etc/init.d/$0 {start|stop|restart|force-reload}" >&2
  ;;
esac

exit 0
